<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\admin\controller\match;

use app\admin\model\review\Record;
use app\common\controller\BackendApi;
use app\common\manager\LogManager;
use app\common\model\ReviewRecord;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 赛事申请管理
 *
 * @icon fa fa-circle-o
 */
class Apply extends BackendApi
{

    /**
     * Apply模型对象
     * @var \app\admin\model\match\Apply
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\match\Apply;
        //$this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['merchant','store','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function edit($ids=null)
    {
        $startTime = microtime(true);
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $maxId = $this->model->where('merchant_id',$row->merchant_id)->where('store_id',$row->store_id)->max('id');
        if ($row->id < $maxId){
            $this->error('当前记录无法修改');
        }

        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $adminInfo = $this->auth->getUserInfo();
            //print_r($adminInfo);
            $insert['apply_id'] = $row->id;
            $insert['review_id'] = $this->auth->id;
            $insert['review_time'] = time();
            $insert['reason'] = $params['reason'];
            $insert['create_time'] = time();
            $insert['update_time'] = time();
            $insert['status'] = $params['status'];
            Record::create($insert);
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'审核赛事申请',
                'data'=>$params,
                'match_id'=>$row->id,
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_APPLY_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

}
